package com.onetech.adrewards.free.fragments;

import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.activities.SocialShareActivity;
import com.onetech.adrewards.free.adapters.ListAdRewardAdapter2;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.customviews.LoadMoreListView;
import com.onetech.adrewards.free.customviews.LoadMoreListView.OnLoadMoreListener;
import com.onetech.adrewards.free.dialogs.AdRewardDetailDialog2;
import com.onetech.adrewards.free.models.AdRewardModel;
import com.onetech.adrewards.free.objects.AdDTO2;
import com.onetech.adrewards.free.objects.RequestParam2;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.todddavies.components.progressbar.ProgressWheel;

public class BaseAdRewardFragment2 extends Fragment implements OnClickListener, OnLoadMoreListener, OnItemClickListener{
	protected View mView;
	protected View mNotFoundData=null;
	protected View mWaitingForLoading=null;
	protected View mBtnRetry=null;
	protected ProgressWheel mProgress=null;
	protected LoadMoreListView mListView;
	
	private ListAdRewardAdapter2 mAdapter;
	private GetListAdFromAdReward mGetListAdReward=null;
	
	protected int pageNo=1;	
	protected String typeCate="appli";
	
	protected String url="";
	protected RequestParam2 mParams=null;
	
	protected String mName="";
	
	protected boolean isTesting=false;
	public static int mCurrentSortMenu = 3;
	protected boolean isNewLoading=false;
	
	protected Tracker mTracker;
	
	protected String mViewTracker="";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mTracker = EasyTracker.getInstance(getActivity());
	}
	protected void initView() {
		mListView = (LoadMoreListView) mView.findViewById(R.id.myListView);
		mListView.setVisibility(View.GONE);
		mAdapter = new ListAdRewardAdapter2(getActivity());
		mListView.setAdapter(mAdapter);
		initNotFoundAndLoadingView();
		mParams=new RequestParam2();
	}
	protected void createURL2(){
		AdrewadsUtils.checkUId();
		url = AppConfig.URLRequestApi.GET_AD  + AppConfig.uId+"?ver=8"; 
		
		if(mParams!=null){
			if(mParams.getSort()!=null){
				url+="&sort="+mParams.getSort();
			}
			if(mParams.getAttribute()!=null && mParams.getAttribute().trim().length()>0){
				url+="&att="+mParams.getAttribute();
			}
			url+="&platform="+mParams.getPlatform();
			addSortParams2();
		}

	}
	protected void addSortParams2(){
		RequestParam2 temp=createSortParams();
		if(temp.getSort()!=null){
			url+="&sort="+temp.getSort();
		}			
	}
	
	protected RequestParam2 createSortParams(){
		RequestParam2 param=new RequestParam2();
		switch (mCurrentSortMenu) {
			case 1:
				param.setSort("1");
				break;
			case 2:
				param.setSort("2");
				break;
			case 3:
				param.setSort("3");
				break;
			case 4:
				param.setSort("4");
				break;
			default:
				break;
		}
		return param;
	}
	
	protected void initListener() {
		initRetryButtonListener();
		mListView.setOnLoadMoreListener(this);
		mListView.setOnItemClickListener(this);
	}
	protected void initNotFoundAndLoadingView(){
		mNotFoundData=(LinearLayout)mView.findViewById(R.id.notFoundDataContainer);		
		mWaitingForLoading=(LinearLayout)mView.findViewById(R.id.waitingLoading);
		mProgress=(ProgressWheel)mView.findViewById(R.id.progressWheel);
		//mProgress.spin();
		showNotFoundOrLoadingView(false, true);
		mBtnRetry=(LinearLayout)mView.findViewById(R.id.btnRetry);
	}
	protected void initRetryButtonListener(){
		mBtnRetry.setOnClickListener(this);
	}
	protected void showNotFoundOrLoadingView(boolean isShowNotFound,boolean isShowLoading){
		if(isShowNotFound){
			mNotFoundData.setVisibility(View.VISIBLE);
		}else{
			mNotFoundData.setVisibility(View.GONE);
		}
		if(isShowLoading){
			mProgress.spin();
			mWaitingForLoading.setVisibility(View.VISIBLE);
		}else{			
			mWaitingForLoading.setVisibility(View.GONE);
			mProgress.stopSpinning();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnRetry:
			pageNo = 1;
			getListAdReward();
			break;
		default:
			break;
		}
	}
	@Override
	public void onLoadMore() {
		getListAdReward();
	}
	protected void getListAdReward(){
		//if(mAdapter!=null && mAdapter.getCount()<1){
		if(mAdapter!=null){
			if(mGetListAdReward==null || mGetListAdReward.getStatus()==Status.FINISHED){
				mGetListAdReward=new GetListAdFromAdReward();
				mGetListAdReward.execute();
			}
		}		
	}
	public void reloadListAdReward(){
		//Toast.makeText(getActivity(), mName, Toast.LENGTH_LONG).show();
		
		pageNo=1;
		if(mGetListAdReward==null || mGetListAdReward.getStatus()==Status.FINISHED){
			mGetListAdReward=new GetListAdFromAdReward();
			mGetListAdReward.execute();
		}
	}
	protected class GetListAdFromAdReward extends AsyncTask<Void, Void, List<AdDTO2>>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showNotFoundOrLoadingView(false, true);
			if(pageNo==1){
				mListView.setVisibility(View.GONE);
			}
		}
		@Override
		protected List<AdDTO2> doInBackground(Void... params) {
			
			if(isTesting){ //just for testing
				return null;
			}
			try {				
				String page=String.valueOf(pageNo);
				//Log.e("URL", url+"&page="+page);
				return AdRewardModel.getInstance().getListAds(url+"&page="+page,typeCate,page,String.valueOf(mCurrentSortMenu));				
			} catch (Exception e) {
				return null;
			}
		}
		@Override
		protected void onPostExecute(List<AdDTO2> result) {
			super.onPostExecute(result);
			if(result!=null && result.size()>0){
				if(pageNo==1){
					mAdapter.updateAppList(result);
				}
				else{
					mAdapter.insertAppList(result);
				}
				pageNo++;
			}
			if(mAdapter.getCount()<1){
				showNotFoundOrLoadingView(true, false);
				mListView.setVisibility(View.GONE);
			}else{
				showNotFoundOrLoadingView(false, false);
				mListView.setVisibility(View.VISIBLE);
			}
			mListView.onLoadMoreComplete();
		}
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		try {
			if(position>mAdapter.getCount()-1){
				return;
			}
			AdDTO2 item=mAdapter.getItem(position);
			if(item==null){
				return;
			}
			
			if("1".equals(item.source) && "2".equals(item.id))
			{
				Intent mSocialShareIntent=new Intent(getActivity(), SocialShareActivity.class);
				startActivity(mSocialShareIntent);
			}
			else
			{
				AdRewardDetailDialog2 mAdRewardDetailDialog=new AdRewardDetailDialog2(getActivity(), item);
				mAdRewardDetailDialog.show();
			}
		} catch (Exception e) {
			return;
		}
	}
	public String getmName() {
		return mName;
	}
	public void setmName(String mName) {
		this.mName = mName;
	}
	protected void initData(){
		pageNo=1;
	}
	protected void loadData(){		
		initData();
		getListAdReward();
		trackingView();
	}
	@Override
	public void onResume() {	
		super.onResume();
		loadData();
	}
	protected void trackingView() {
        try {
            mTracker.set(Fields.SCREEN_NAME, mViewTracker);            
            mTracker.send(MapBuilder.createAppView().build());            
		} catch (Exception e) {
		}
	}
	protected void setViewTracker(int resId){
		mViewTracker=getActivity().getString(resId);
	}
}
